export const NoteModel = {
  async findByUser(env, email) {
    const stmt = env.DB.prepare(`
      SELECT n.* FROM notes n
      INNER JOIN users u ON n.user_id = u.id
      WHERE u.email = ?
      ORDER BY n.created_at DESC
    `)
    return await stmt.bind(email).all()
  },

  async create(env, { userId, title, titleIv, content, contentIv }) {
    const stmt = env.DB.prepare(`
      INSERT INTO notes (
        user_id, title, title_iv,
        content, content_iv
      ) VALUES (?, ?, ?, ?, ?)
    `)
    return await stmt.bind(
      userId, title, titleIv,
      content, contentIv
    ).run()
  },

  async update(env, id, data) {
    const sets = []
    const values = []
    
    if (data.title) {
      sets.push('title = ?')
      values.push(data.title)
    }
    
    if (data.titleIv) {
      sets.push('title_iv = ?')
      values.push(data.titleIv)
    }
    
    if (data.content) {
      sets.push('content = ?')
      values.push(data.content)
    }
    
    if (data.contentIv) {
      sets.push('content_iv = ?')
      values.push(data.contentIv)
    }
    
    if (sets.length === 0) return null
    
    values.push(id)
    const query = `UPDATE notes SET ${sets.join(', ')}, updated_at = DATETIME('now') WHERE id = ?`
    
    const stmt = env.DB.prepare(query)
    return await stmt.bind(...values).run()
  },

  async delete(env, id) {
    const stmt = env.DB.prepare('DELETE FROM notes WHERE id = ?')
    return await stmt.bind(id).run()
  }
} 